<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;

class UserRelations extends Model
{
    use SoftDeletes;
    protected $table = 'user_relations';

    /**
     * 定义主键
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * 禁止批量赋值的字段
     *
     * @var array
     */
    protected $guarded = ['id','created_at','deleted_at'];


    /**
     * 软删除应该被调整为日期的属性
     * [$dates description]
     * @var [type]
     */
    protected $dates=[
        'created_at', 'updated_at','deleted_at'
    ];


    /*
     * 生成 并 存储邀请码、
     * @return string
     */
    public static function store($user_id)
    {

        if(!$userRelation = self::where('user_id',$user_id) -> first()){
            $invite_code = rand_string(8);
            $param = [
                'invite_code'   => $invite_code,
                'invite_qrcode' => null,
                'invite_num' => 0,
                'user_id'    => $user_id,
            ];
            $userRelation = self::create($param);
        }

        return $userRelation;
    }

    /*
     * 邀请人数自增
     */
    public static function inviteInc($invite_code)
    {

        if($userRelation = self::where('invite_code',$invite_code) -> first()){

            $res = $userRelation -> increment('invite_num');
            return $res ? true : false;
        }

        return false;
    }


    /*
     * 存储自己的邀请人 是 谁
     *
     */
    public static function storeInviter($invite_code)
    {

        if($userRelation = self::where('invite_code',$invite_code) -> first()){


            $user_id = auth() -> id();

            DB::beginTransaction();
            $user = User::find($user_id);

            if($user -> inviter_user_id){
                return ['error' => 4035];
            }

            $user -> inviter_user_id = $userRelation ->user_id;
            $res1 = $user -> save();
            $res2 = $userRelation -> increment('invite_num');


            if($res1 && $res2){
                DB::commit();
                return true;
            }else{
                DB::rollBack();
                return false;
            }
        }

        return false;

    }
}
